package com.lsl.gulimall.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.lsl.common.constant.CommonConstant;
import com.lsl.common.utils.R;
import com.lsl.gulimall.member.dao.MemberLevelDao;
import com.lsl.gulimall.member.entity.MemberLevelEntity;
import com.lsl.gulimall.member.vo.MemberRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsl.common.utils.PageUtils;
import com.lsl.common.utils.Query;

import com.lsl.gulimall.member.dao.MemberDao;
import com.lsl.gulimall.member.entity.MemberEntity;
import com.lsl.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R saveMember(MemberRegisterVo memberRegisterVo) {
        List<MemberEntity> memberEntityList = this.list(new LambdaQueryWrapper<MemberEntity>()
                .eq(MemberEntity::getMobile, memberRegisterVo.getPhoneNum())
                .or().eq(MemberEntity::getEmail, memberRegisterVo.getEmail()));
        if (CollectionUtils.isNotEmpty(memberEntityList)) {
            return R.error(500, "存在已经注册的用户");
        }
        MemberLevelEntity memberLevelEntity = memberLevelDao.selectOne(new LambdaQueryWrapper<MemberLevelEntity>()
                .eq(MemberLevelEntity::getDefaultStatus, CommonConstant.DEFAULT_LEVEL)
        );
        if (ObjectUtils.isEmpty(memberLevelEntity)) {
            return R.error(500, "没有默认等级");
        }
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setUsername(memberRegisterVo.getUserName());
        memberEntity.setPassword(memberRegisterVo.getPassWord());
        memberEntity.setMobile(memberRegisterVo.getPhoneNum());
        memberEntity.setEmail(memberRegisterVo.getEmail());
        memberEntity.setCreateTime(new Date());
        memberEntity.setLevelId(memberLevelEntity.getId());
        if (this.save(memberEntity)) {
            return R.ok("注册会员成功");
        }
        return R.error(500, "注册会员失败");
    }

}